﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Net;

namespace BioBooking.WebClient
{
    /// <summary>
    /// Summary description for image
    /// </summary>
    public class image : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/png";
            BioBooking.Data.BioBookingContainer container = new Data.BioBookingContainer();

            int screenID = 0;
            int.TryParse(HttpContext.Current.Request.QueryString["id"], out screenID);

            var screen = container.ScreenShotSet.FirstOrDefault(p => p.Id == screenID);

            if (screen == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                context.Response.End();
            }

            MemoryStream stream = new MemoryStream(screen.Image);
            Bitmap bitmap = new Bitmap(stream);

            int height;
            int width;

            bool heightParsed = int.TryParse(HttpContext.Current.Request.QueryString["h"], out height);
            bool widthParsed = int.TryParse(HttpContext.Current.Request.QueryString["w"], out width);

            if (!heightParsed)
                height = bitmap.Height;

            if (!widthParsed)
                width = bitmap.Width;

            if (heightParsed && !widthParsed)
            {
                width = (int)(((double)bitmap.Width / (double)bitmap.Height) * (double)height);
            }

            if (widthParsed && !heightParsed)
            {
                height = (int)(((double)bitmap.Height / (double)bitmap.Width) * (double)width);
            }

            ImageManipulator manipulator = new ImageManipulator();
            Bitmap resized = manipulator.ResizeImage(bitmap, width, height);

            MemoryStream imageStream = new MemoryStream();
            resized.Save(imageStream, ImageFormat.Png);

            context.Response.BinaryWrite(imageStream.ToArray());
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}